package com.scs.application.core.aliyun.sms.handler;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.scs.application.core.aliyun.sms.properties.AliyunSmsProperties;
import com.google.gson.Gson;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Slf4j
@NoArgsConstructor
public class AliyunSmsHandler {
    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    public boolean sendSms(String phone, String templateCode, Map<String, Object> params) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSmsProperties.getRegion(), this.aliyunSmsProperties.getAccessKeyId(), this.aliyunSmsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(this.aliyunSmsProperties.getDomain());
        request.setVersion(this.aliyunSmsProperties.getVersion());
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSmsProperties.getRegion());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", this.aliyunSmsProperties.getSign());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", params != null ? (new Gson()).toJson(params) : "");

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getData().indexOf("\"Code\":\"OK\"") != -1;
        } catch (ClientException var8) {
            log.error("短信发送失败", var8);
            return false;
        }
    }
}
